<script setup lang="ts">
import { ref, watchEffect,watch } from 'vue';
import Public from '../../components/Public.vue'
import { userListApi,delApi, exportApi } from '../../services';
import type { userItem } from '../../services/type'
import Dialog from './components/Dialog.vue';
import { ElMessageBox,ElMessage } from 'element-plus'
import Search from './components/Search.vue';
import * as XLSX from 'xlsx';


const tableData = ref<userItem[]>([])
const total = ref(0)
const editList = ref<userItem | null>(null)

const params = ref({
    page:1,
    pagesize:5
  })
const otherParams = ref([]) 

const visible = ref(false)
const selection = ref<userItem[]>([])

// 调取用户列表接口
const getList = async () => {
  const res = await userListApi({
    ...params.value,
    ...otherParams.value
  })
  // console.log(res.data.values)
  tableData.value = res.data.values.list
  total.value = res.data.values.total
}


// 编辑按钮  函数
const edit = (row: userItem) => {
  // console.log(row)
  editList.value = row
  visible.value = true
}
// 监听 如果visible为假 则将传给子组件的编辑反显变量改为空
watch(visible, () => {
  if (!visible.value) {
    editList.value = null
  }
})

// 删除按钮调取的删除函数
const del = (row: userItem) => {
  console.log(row)
  ElMessageBox.confirm('确定要删除此用户吗？',{ 
    type:'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  })
    .then(() => {
      delRow(row.id)
    })
    .catch(() => {

    })
}
// 删除函数  获取删除接口
const delRow = async (id: string) => {
  const res = await delApi(id)
  // console.log(res)
  if(res.data.code === 0) {
    ElMessage.success('删除成功')
    getList()
  }else {
    ElMessage.error(res.data.msg)
  }
}

// 接受子组件传过来的参数
const onSearch = (val: any) => {
  console.log('接受父组件传过来的参数',val)
  otherParams.value = val
}


// 自动监听页面数据变量改变
watchEffect(() => {
  getList()
})



// 导出数据
// 纯前端
const exportExcelFE = () => {
  // console.log(selection.value)
  const data = selection.value.map(item => {
    return {
      '序号':item.no,
      '用户ID':item.id,
      '性别':item.sex,
      '年龄':item.age,
      '用户名':item.username,
      '密码':item.password,
      '邮箱':item.email
    }
  })
// 创建一个表格对象
  const workbook = XLSX.utils.book_new()
// 根据json生成一个 sheet
  const worksheet = XLSX.utils.json_to_sheet(data)
// 把 sheet 添加到 book 对象中
  XLSX.utils.book_append_sheet(workbook, worksheet, '第一页')
// 导出excel
  XLSX.writeFile(workbook, '用户数据.xlsx');
}

// 后端接口
const exportExcelRD = async () => {
  // 先获取id
  const ids = selection.value.map(item => item.id)
  //调取接口  
  const res = await exportApi(ids)
  // console.log(res)
  // 创建一个地址  读取后端返回的文件的临时地址
  const url = window.URL.createObjectURL(res.data)
  // 下载到本地  用a标签进行下载（图片，文件） 先创建a标签 
  const a = document.createElement('a')
  a.href = url
  // 下载到本地  文件名 
  a.download = '用户列表.xlsx'
  // 追加在页面
  document.body.appendChild(a)
  // 调用点击事件
  a.click()
  // 移除  释放内存  减少性能损耗
  document.body.removeChild(a)
  // 释放内存
  window.URL.revokeObjectURL(url)
}





// 调用后端接口



// 导出数据函数
const exportExcel = () => {
  // console.log(selection.value)
  // 前端
  // exportExcelFE()
  
  // 后端
  exportExcelRD()

}


// 触发选框事件
const onSelect = (datas: userItem[]) => {
  // console.log(datas)
  selection.value = datas

}


</script>

<template>
  <Public>
    <!-- 查询 -->
    <Search @search = 'onSearch'/>

    <el-button type="primary" class="add" @click="visible = true">新增</el-button>
    <el-button type="primary" class="add" @click="exportExcel">导出数据</el-button>

    <!-- 表格 -->
    <el-table :data="tableData" style="width: 100%" @selection-change="onSelect">
      <el-table-column type="selection" width="55" fixed="left"/>
      <el-table-column prop="no" label="序号" width="70" fixed="left"/>
      <el-table-column prop="id" label="用户id" width="180" />
      <el-table-column prop="username" label="姓名" />
      <el-table-column prop="sex" label="性别" >
        <template #default="scope">
          <el-tag>{{ scope.row.sex === 1? '男':'女' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="age" label="年龄" />
      <el-table-column prop="email" label="邮件" width="200"/>
      <el-table-column prop="password" label="密码" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="edit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="del(scope.row)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <!-- 分页器 -->
    <el-pagination
      class="pagination"
      v-model:current-page="params.page"
      v-model:page-size="params.pagesize"
      :page-sizes="[5, 10, 20, 30]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    />
    <!-- 点击新增  -->
    <Dialog 
      v-model:visible = "visible"
      :editList = "editList"
      @refresh = getList
    />
    <!-- @update:visible = "visible = $event" -->

  </Public>
  

</template> 

<style lang="scss" scoped>
.add{
  margin: 10px 0;
}
.pagination{
  margin-top: 15px;
  justify-content: flex-end;
}
</style>
